package com.fuzongle.tank.core.config;

import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;


import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
 * 
 * @Description:解决前后端分离前端请求跨域问题
 * @author: fuzongle   
 * @date: 2019年3月12日 下午3:44:58
 */
@Component
public class CorsFilter extends OncePerRequestFilter {
    @Override
	protected void doFilterInternal(HttpServletRequest request,  HttpServletResponse response, FilterChain filterChain)  throws ServletException, IOException {
        response.addHeader("Access-Control-Allow-Origin", "*");
        if (request.getHeader("Access-Control-Request-Method") != null && "OPTIONS".equals(request.getMethod())) {
            // CORS "pre-flight" request
            response.addHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE");
            response.addHeader("Access-Control-Allow-Headers", "Content-Type");
            response.addHeader("Access-Control-Max-Age", "1");// 30 min
        }
        filterChain.doFilter(request, response);
    }
    
}
